using System;
using System.IO;
using Slaks.DocumentSerialization.Document;
using Slaks.Graphs;
using Slaks.Graphs.GraphBuilder.Slaks;

namespace Slaks.VisualGraphConstruction
{
	public class VisualGraphConstructor
	{
		string m_input_graph_file;
		string m_output_graph_file;
		public VisualGraphConstructor(string input_graph_file,string output_graph_file)
		{
			m_input_graph_file = input_graph_file;
			m_output_graph_file = output_graph_file;
		}

		public void Construct()
		{
			StreamWriter writer = null;

			try
			{
				writer = new StreamWriter(m_output_graph_file);
				Document document = Xml2Document.ReadXml(m_input_graph_file);

				StandardRepresentationSlaks standardRepresentation = new StandardRepresentationSlaks();
				Graph graph = standardRepresentation.Build(document,20);

				this.OpenGraph(writer);

				this.ProcessNode(writer,document,graph);

				this.CloseGraph(writer);
			}
			catch(IOException ex)
			{
				Console.WriteLine(ex.Message);
			}
			finally
			{
				if (writer != null) writer.Close();
			}
		}

		private void OpenGraph(StreamWriter writer)
		{
			writer.WriteLine("digraph graphic { size = \"300,300\" ");
		}

		private void CloseGraph(StreamWriter writer)
		{
			writer.WriteLine(" } ");
		}

		private void ProcessNode(StreamWriter writer,Document document,Graph graph)
		{
			foreach(Vertex vertex in graph.GetVertexList())
			{
				long id = vertex.GetId();
				Node node = document.GetNodeById(id);
				
				SectionType2EdgeListMap sectionType2EdgeListMap = vertex.GetSection2EdgeMap();
				if (sectionType2EdgeListMap == null || sectionType2EdgeListMap.Count == 0)
				{
				  writer.WriteLine(node.Term + "_id_" + id);	
					continue;
				}
				
				foreach(string sectionType in sectionType2EdgeListMap.Keys)
				{
					EdgeList edgeList = sectionType2EdgeListMap[sectionType];
					foreach(Edge edge in edgeList)
					{
						Vertex target = edge.GetTarget();
						Node nodeTarget  = document.GetNodeById(target.GetId());
						writer.WriteLine(node.Term + "_id_" + id + " -> " + nodeTarget.Term + "_id_" + nodeTarget.Id + " [ label = \"" + sectionType + "\" ];\n");
					}
					
				}
			}
			/*
			foreach(Section section in node.Sections)
			{
				foreach(Sentence sentence in section.Sentences)
				{
					writer.Write(node.Term);
					if (sentence.NextId >= 0)
					{
						string nextTerm = document.GetNodeById(sentence.NextId).Term;
						writer.Write(" -> " + nextTerm + " [ label = \"" + section.GetSectionTypeString() + "\" ];\n");
					}
					writer.WriteLine("");
				}
			}
			*/

			
		}
	}
}
